import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import {Image, View, /*Text*/} from '@tarojs/components'
import { SDBody, SDLoading, SDSlide } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout, setShopCart } from '../../../redux/actions'
import GoodsItem from '../../../comps/goods-item'
import SDButton from '../../../comps/sd-button'
import { CART_PARAMS_KEY } from '../../../redux/constants'

import './index.less'


import EmptyIcon from '../../../images/ic_no_items.png'
import NextIcon from '../../../images/ic_next.png'
import CheckNorIcon from '../../../images/ic_check_nor.png'
import SKUPicker from "../../../comps/sku-picker";
import CheckPreIcon from '../../../images/ic_check_pre.png'

type PageState = {
  mainIsLoading: boolean,
  loading: boolean,
  hasData: boolean,
  hasMore: boolean,
  hideLoading: boolean,
  dataList: any[],
  invalidDataList: any[],
  silverPriceData: any,         // 今日银价
  totalPrice: number,           // 应付价
  totalGoodsCount: number,      // 选中的商品数
  totalSpecCount: number,       // 选中的规格数
  totalQuantity: number,        // 选中的总个数
  isAllSelected: boolean,       // 是否全选
  btnIsLoading: boolean,        // 结算按钮是否正在加载中
  productList: any[]
}

type PageOwnProps = {}

interface TabBarCartPage {
  props: PageProps & PageOwnProps
}

@connect(({userState, cartState}) => ({
  userState,
  cartState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  },
  setShopCart(cartData) {
    dispatch(setShopCart(cartData))
  }
}))
class TabBarCartPage extends Component<PageOwnProps, PageState> {

  constructor () {
    super()
    this.state = {
      mainIsLoading: true,
      loading: false,
      hasData: true,
      hasMore: true,
      dataList: [],
      invalidDataList: [],
      hideLoading: true,
      silverPriceData: {},
      totalPrice: 0,
      totalGoodsCount: 0,
      totalQuantity: 0,
      totalSpecCount: 0,
      isAllSelected: false,
      btnIsLoading: false,
      productList: []
    }
  }

  config: Config = {
    navigationBarTitleText: '购物车',
    enablePullDownRefresh: true
  }

  preEditingSlideID: string = ''
  cartList: any[] = []
  invalidCartList: any[] = []

  render () {
    const {
      hasData,
      invalidDataList,
      dataList,
      totalPrice,
      totalGoodsCount,
      totalQuantity,
      totalSpecCount,
      isAllSelected,
      btnIsLoading,
      productList
    } = this.state
    // const flag = true
    // const flag2 = true

    return (
      <SDBody sd-class='container' showPadding={false}>
        {
          dataList.length > 0 ? (
            <View className='section section-normal'>
              {
                dataList.map((item, index) => {
                  return (
                    <View className='cell-item' key={index} onClick={this.onCellTaped.bind(this, index, 'normal')}>
                      <SDSlide
                        id={`comps-slide_normal_${index}`}
                        height={200}
                        slideWidth={160}
                        renderSlide={
                          <View className='cell-item__delete' data-index={index} data-style='normal' onClick={this.onDeleteBtnTaped}>删除</View>
                        }
                        extData={({
                          index: index,
                          type: 'normal'
                        })}
                        onWillEditing={this.onCellWillEditing}
                      >
                        <View className="cell-content">
                          <View className="cell-left" onClick={this.onCheckBtnTaped.bind(this, index)}>
                            <Image className="select-icon" src={item.selected ? CheckPreIcon : CheckNorIcon}></Image>

                            {/*<Text className="cell-left__title">*/}
                              {/*库存\n不足*/}
                            {/*</Text>*/}
                          </View>
                          <View className="cell-right">
                            <Image className="cell-img" src={SDUtils.processImageURL(item.coverImage || '', 336, 336)} lazyLoad mode='aspectFill'></Image>
                            <View className="cell-i_right">
                              <View className="cell-title">{item.name}</View>
                              <View className="cell-i_bottom">
                                <View className="cell-ib_left">
                                  <View className="cell-price">{SDUtils.formatPrice(`${item.calcPrice}`)}</View>
                                  <View className="cell-ib_bottom">
                                    <View className="cell-ibb_item">
                                      <View className="title">规格:</View>
                                      <View className="tips">{item.specVos.length}</View>
                                    </View>
                                    <View className="cell-ibb_item">
                                      <View className="title">总数:</View>
                                      <View className="tips">{item.quantity}</View>
                                    </View>
                                  </View>
                                </View>
                                <View className="cell-ib_right" onClick={this.onCartIconTaped.bind(this, index)}>
                                  <View className="normal-btn">修改</View>
                                </View>
                              </View>
                            </View>
                          </View>
                        </View>
                      </SDSlide>

                      <View className='sku-tips__content'>
                        <View className='left'></View>
                        <View className='right'>
                          <View className='sku-tips_inner'>
                            <View className='sku-tips_title'>
                              {item.specVosTitle}
                            </View>
                          </View>
                        </View>
                      </View>
                    </View>
                  )
                })
              }
            </View>
          ) : null
        }

        {
          invalidDataList.length > 0 ? (
            <View className='section section-invalid'>
              <View className="invalid-header">
                <View className="header-title">失效宝贝50件</View>
                <View className="header-btn">
                  <View className="header-btn__title">清空失效宝贝</View>
                </View>
              </View>
              {
                invalidDataList.map((_, index) => {
                  return (
                    <View className='cell-item border-bottom_1px' key={index} onClick={this.onCellTaped.bind(this, index, 'invalid')}>
                      <SDSlide
                        id={`comps-slide_invalid_${index}`}
                        height={200}
                        slideWidth={160}
                        renderSlide={
                          <View className='cell-item__delete' data-index={index} data-style='invalid' onClick={this.onDeleteBtnTaped}>删除</View>
                        }
                        extData={({
                          index: index,
                          type: 'invalid'
                        })}
                        onWillEditing={this.onCellWillEditing}
                      >
                        <View className="cell-content">
                          <View className="cell-left">
                            <View className="cell-left__invalid-title">
                              失效
                            </View>
                          </View>
                          <View className="cell-right">
                            <Image className="cell-img" src='' lazyLoad mode='aspectFill'></Image>
                            <View className="cell-i_right">
                              <View className="cell-title">银河系925银叠戴基础手镯</View>
                              <View className="cell-i_bottom">
                                <View className="cell-ib_left">
                                  <View className="cell-price">¥ 500</View>
                                  <View className="cell-ib_bottom">
                                    <View className="cell-ibb_item">
                                      <View className="title">规格:</View>
                                      <View className="tips">30</View>
                                    </View>
                                    <View className="cell-ibb_item">
                                      <View className="title">总数:</View>
                                      <View className="tips">500</View>
                                    </View>
                                  </View>
                                </View>
                              </View>
                            </View>
                          </View>
                        </View>
                      </SDSlide>

                      <View className='sku-tips__content'>
                        <View className='left'></View>
                        <View className='right'>
                          <View className='sku-tips_inner'>
                            <View className='sku-tips_title'>
                              20克经典开口款；16克经典开口款；10克经典开口款；16克叠戴基础款
                            </View>
                          </View>
                        </View>
                      </View>
                    </View>
                  )
                })
              }
            </View>
          ) : null
        }

        {
          dataList.length > 0 ? (
            <View className="main-bottom">
              <View style='height: 156rpx;'></View>
              <View className="fixed-bottom border-top_1px">
                <View className="check-btn" onClick={this.onAllCheckBtnTaped}>
                  <Image className="icon" src={isAllSelected ? CheckPreIcon : CheckNorIcon}></Image>
                  <View className="title">全选</View>
                </View>
                <View className="center">
                  <View className="center-top">
                    <View className="tips">合计：</View>
                    <View className="price">{SDUtils.formatPrice(`${totalPrice}`)}</View>
                  </View>
                  <View className="center-bottom">
                    <View className="cb-item">商品:{totalGoodsCount}</View>
                    <View className="cb-item">规格:{totalSpecCount}</View>
                    <View className="cb-item">总数:{totalQuantity}</View>
                  </View>
                </View>
                <SDButton sd-class='submit-btn' height={96} loading={btnIsLoading} onClick={this.gotoOrderPreviewPage}>去结算</SDButton>
              </View>
            </View>
          ) : null
        }

        <SDLoading loading={false} hasData={hasData} hasMore={false}>
          <View className='main-empty'>
            <View className='header'>
              <Image className='icon' src={EmptyIcon}></Image>
              <View className='title'>购物车是空的～</View>
            </View>
            <View className='content'>
              <View className='section-header'>
                <View className='title'>推荐商品</View>
                <View className='right' onClick={this.onMoreBtnTaped}>
                  <View className='item'>
                    <View className='item-title'>更多</View>
                    <View className='item-icon-content'>
                      <Image className='ic-next' src={NextIcon}></Image>
                    </View>
                  </View>
                </View>
              </View>
              <View className='empty-list'>
                {
                  productList.map((item, index) => {
                    return (
                      <View className='empty-cell' key={index}>
                        <GoodsItem
                          extData={index}
                          width={336}
                          height={502}
                          imgUrl={item.coverImage || ''}
                          title={item.name}
                          price={SDUtils.formatPrice(`${item.minPrice}`)}
                          showTagPrice={true}
                          tagPrice={SDUtils.formatPrice(`${item.minTagPrice}`)}
                          showCartNum={false}
                          cartNum={0}
                          showSalesVolume={true}
                          salesVolume='998'
                          bgColor='#fff'
                          type='recommend'
                          onClick={this.gotoGoodsDetail}
                          onCartClick={this.onCartIconTaped}
                          showCartIcon={true}
                        />
                      </View>
                    )
                  })
                }
              </View>
            </View>
          </View>
        </SDLoading>


        <SKUPicker ref='compsSkuPicker' onSelect={this.onSkuSelect}/>
      </SDBody>
    )
  }

  onPullDownRefresh () {
    this.fetchData()
  }

  componentWillReceiveProps (nextProps) {
    const { cartState: { cartList = [], invalidCartList = [] } = {} } = nextProps

    let preDataList = this.state.dataList
    // let preInvalidDataList = this.state.invalidDataList

    let dataList: any[] = []
    let invalidDataList: any[] = []
    for (let i = 0; i < cartList.length; i++) {
      let cartItem = cartList[i]
      let productVos = cartItem.productVos || []
      dataList.push(...productVos)
    }

    dataList = dataList.map(item => {
      let preItem = preDataList.find(ele => ele.productId == item.productId)
      item.selected = false
      if (preItem) {
        item.selected = preItem.selected
      }
      let specVosTitle = ''
      let skuVos = item.skuVos || []
      for (let i = 0; i < skuVos.length; i++) {
        let skuItem = skuVos[i] || {}
        let itemTitle = (skuItem.specItems || []).map(innerItem => innerItem.attrValue || '').join(' ')
        specVosTitle += `${itemTitle}；`
      }
      if (specVosTitle.length > 0) {
        specVosTitle = specVosTitle.substr(0, specVosTitle.length - 1)
      }
      item.specVosTitle = specVosTitle
      return item
    })
    this.cartList = dataList
    this.invalidCartList = invalidDataList

    this.setState({
      hasData: dataList.length > 0 || invalidCartList.length > 0
    },async() => {
      try {
        let silverPriceData = await SDUtils.doGet('/wxmini/silverPrice/newest')
        silverPriceData.price = silverPriceData.price || 0
        this.setState({
          silverPriceData: silverPriceData
        }, () => {
          this.calcPrice()
        })
      } catch (e) {
        SDUtils.showMsg(e)
      } finally {
        Taro.stopPullDownRefresh()
      }
    })
  }

  componentDidMount () {
    this.fetchData()
  }

  calcPrice = () => {
    let { silverPriceData } = this.state
    let dataList = this.cartList || []
    let invalidDataList = this.invalidCartList || []

    let totalPrice = 0           // 应付价
    let totalGoodsCount = 0      // 选中的商品数
    let totalSpecCount = 0       // 选中的规格数
    let totalQuantity = 0        // 选中的总个数

    dataList = dataList.map(item => {
      let calcPrice = 0
      item.processFee = item.processFee || 0

      let skuList = item.skuVos || []

      for (let i = 0; i < skuList.length; i++) {
        let skuItem = skuList[i]
        skuItem.quantity = skuItem.quantity || 0
        skuItem.weight = skuItem.weight || 0

        calcPrice += skuItem.quantity * skuItem.weight * (silverPriceData.price + item.processFee)
      }
      item.specVos = skuList
      item.calcPrice = calcPrice

      if (item.selected) {
        totalPrice += item.calcPrice
        totalGoodsCount += 1
        for (let i = 0; i < skuList.length; i++) {
          let specVosItem = skuList[i]
          if (specVosItem.quantity > 0) {
            totalSpecCount += 1
            totalQuantity += specVosItem.quantity
          }
        }
      }
      return item
    })
    let isAllSelected = dataList.filter(item => !item.selected).length <= 0
    this.setState({
      totalPrice: totalPrice,
      totalSpecCount: totalSpecCount,
      totalQuantity: totalQuantity,
      totalGoodsCount: totalGoodsCount,
      mainIsLoading: false,
      loading: false,
      dataList: dataList,
      invalidDataList: invalidDataList,
      isAllSelected: isAllSelected
    })
  }

  fetchData = async () => {
    let { loading } = this.state
    if (loading) { return }
    this.setState({loading: true},async () => {
      try {
        const resp = await SDUtils.doGet('/wxmini/cart')
        let dataList = resp.cartItemVos || []
        let invalidDataList = []
        let productList = []
        if (dataList.length == 0 && invalidDataList.length == 0) {
          let productResp = await SDUtils.doGet('/wxmini/traderProduct', {
            offset: 0,
            limit: 20,
            traderId: '1'
          })
          productList = productResp.items || []
          this.setState({
            productList: productList
          })
        }
        this.props.setShopCart({
          cartList: dataList,
          invalidCartList: invalidDataList
        })
        Taro.hideLoading()
      } catch (e) {
        SDUtils.showMsg(e)
        Taro.stopPullDownRefresh()
        this.setState({loading: false})
      }
    })

  }

  closePreEditingCell = () => {
    if (!this.preEditingSlideID) { return }
    let comps = (this.$scope.selectComponent(`#${this.preEditingSlideID}`) || {}).$component
    comps && comps.endEditing()
    this.preEditingSlideID = ''
  }

  onCellWillEditing = (extData: any) => {
    let currentEditingSlideID = `comps-slide_${extData.type}_${extData.index}`
    if (this.preEditingSlideID && this.preEditingSlideID != currentEditingSlideID) {
      this.closePreEditingCell()
    }
    this.preEditingSlideID = currentEditingSlideID
  }

  onDeleteBtnTaped = (e) => {
    e.stopPropagation()
    let sectionStyle = e.currentTarget.dataset.style || ''
    let index = e.currentTarget.dataset.index
    let list: any[] = []
    if (sectionStyle == 'normal') {
      list = this.state.dataList
    } else if (sectionStyle == 'invalid') {
      list = this.state.invalidDataList
    }
    if (list.length <= index) {
      return
    }
    let productId = (list[index] || {}).productId
    if (!productId) {
      SDUtils.showMsg('商品ID非法')
      return
    }
    this.deleteCartItem(productId, index, sectionStyle)
  }

  deleteCartItem = async (productId, index, sectionStyle) => {
    let currentEditingSlideID = `comps-slide_${sectionStyle}_${index}`
    let comps = (this.$scope.selectComponent(`#${currentEditingSlideID}`) || {}).$component

    let result = await Taro.showModal({
      title: '温馨提示',
      content: '您确定要删除吗？'
    })
    let confirm = result.confirm || false
    if (confirm) {
      Taro.showLoading({
        title: '加载中...'
      })
      comps && comps.endEditing()
      await SDUtils.doDelete(`/wxmini/cart/${productId}/product`)

      setTimeout(() => {
        this.fetchData()
      }, 1000)
    } else {
      comps && comps.endEditing()
    }
  }

  onCheckBtnTaped = (index: number, e) => {
    e.stopPropagation()
    let { dataList } = this.state
    dataList[index].selected = !dataList[index].selected
    let isAllSelected = dataList.filter(item => !item.selected).length == 0
    this.setState({
      dataList: dataList,
      isAllSelected: isAllSelected
    }, () => {
      this.calcPrice()
    })
  }

  onAllCheckBtnTaped = () => {
    let {dataList, isAllSelected} = this.state
    isAllSelected = !isAllSelected
    dataList = dataList.map(item => {
      item.selected = isAllSelected
      return item
    })
    this.setState({
      isAllSelected,
      dataList
    }, () => {
      this.calcPrice()
    })
  }

  onMoreBtnTaped = () => {
    SDUtils.jumpTo('/pages/goods/list/index', {comeFrom: 'recommend'})
  }

  onCartIconTaped = (index: number, e) => {
    e.stopPropagation && e.stopPropagation()
    const { dataList } = this.state
    if (index >= dataList.length) { return }
    let item = dataList[index] || {}
    let productId = item.productId
    if (!productId) {
      SDUtils.showMsg('商品ID无效')
      return
    }
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.show(productId)
  }

  onSkuSelect = () => {
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.dismiss()
  }

  onCellTaped = (index: any, type: string) => {
    let currentEditingSlideID = `comps-slide_${type}_${index}`
    if (this.preEditingSlideID != currentEditingSlideID) {
      let comps = (this.$scope.selectComponent(`#${currentEditingSlideID}`) || {}).$component
      comps && comps.endEditing()
    }

    if (this.preEditingSlideID) {
      this.closePreEditingCell()
      return
    }
    if (type == 'invalid') {
      return
    }
    const { dataList } = this.state
    let dataItem = dataList[index]
    if (!dataItem || !dataItem.productId) {
      SDUtils.showMsg('商品ID非法')
      return
    }
    SDUtils.jumpTo('/pages/goods/detail/index', { productId: dataItem.productId})
  }

  gotoGoodsDetail = (index: any) => {
    const { productList = [] } = this.state
    if (productList.length <= index) {
      return
    }
    let productItem = productList[index]
    SDUtils.jumpTo('/pages/goods/detail/index', { productId: productItem.productId})
  }

  gotoOrderPreviewPage = () => {
    const { btnIsLoading, dataList } = this.state
    if (btnIsLoading) {
      return
    }
    let list = dataList.filter(item => item.selected)
    if (list.length == 0) { return }
    let orderItems: any[] = []
    for (let i = 0; i < list.length; i++) {
      let productItem = list[i];
      let skuVos = productItem.skuVos || []
      for (let j = 0; j < skuVos.length; j++) {
        let skuItem = skuVos[j]
        orderItems.push({
          skuId: skuItem.skuId,
          quantity: skuItem.quantity,
        })
      }
    }
    Taro.setStorageSync(CART_PARAMS_KEY, orderItems)

    SDUtils.jumpTo('/pages/order/preview/index')
  }
}

export default TabBarCartPage as ComponentClass<PageOwnProps, PageState>
